/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年6月24日
 */
package com.massyframework.beanskin.graphql.util.pagelist;

import java.util.Map;
import java.util.Objects;

import graphql.schema.DataFetchingEnvironment;

/**
 * 分页请求
 * @author huangkh
 *
 */
public class PageRequest {
	
	private int index;
	private int size;

	/**
	 * 
	 */
	protected PageRequest(Builder builder) {
		this.index = Objects.requireNonNull(builder.index, "\"index\" cannot be null.");
		this.size = Objects.requireNonNull(builder.size, "\"size\" cannot be null.");
	}
	
	
	/**
	 * 当前页号
	 * @return {@link int}
	 */
	public int getIndex() {
		return index;
	}


	/**
	 * 页内记录数
	 * @return {@link int}
	 */
	public int getSize() {
		return size;
	}

	/**
	 * 创建构建器
	 * @return {@link Builder}
	 */
	public static Builder newBuilder() {
		return new Builder();
	}
	
	/**
	 * 基于{@code env}和{@code name}创建构建器
	 * @param env {@link DataFetchingEnvironment}, 数据获取环境
	 * @param name {@link String},参数名
	 * @return {@link Builder}
	 */
	public static Builder newBuilder(DataFetchingEnvironment env, String name) {
		Map<String, Object> map = env.getArgument(name);
		Objects.requireNonNull(map, "argument \"" + name + "\" cannot be null.");
		
		Integer index = (Integer)map.get("index");
		Integer size = (Integer)map.get("size");
		
		return new Builder()
				.index(index)
				.size(size);
	}

	/**
	 * 构建器
	 * @author huangkh
	 *
	 */
	public static class Builder {
		
		private Integer index;
		private Integer size;
		
		/**
		 * 设置当前页索引
		 * @param value {@link Integer}
		 * @return {@link Builder}
		 */
		public Builder index(Integer value) {
			this.index = value;
			return this;
		}
		
		/**
		 * 设置页面记录数量
		 * @param value
		 * @return
		 */
		public Builder size(Integer value) {
			this.size = value;
			return this;
		}
		
		public PageRequest build() {
			return new PageRequest(this);
		}
	}

}
